const jwt = require('jsonwebtoken');
const db = require('../db/db.js');
const { encryptToken } = require('../utils/encrypt.js');

module.exports = (request, response, next) => {
  const url = request.originalUrl;
  // 不需要验证token的接口
  const urlList = [
    '/api/create_mysql_table',
    '/api/register',
    '/api/login',
    '/api/get_goods',
    '/api/get_goods_category',
    '/api/get_goods_brand',
    '/api/get_store_goods_category',
    '/api/get_code'
  ];

  let isUrl = urlList.some(item => url.includes(item));
  if (isUrl) {
    return next();
  }

  // 验证token
  const tokenHeader = request.headers?.authorization || '';
  const token = tokenHeader.startsWith('Bearer ') ? tokenHeader.slice(7) : tokenHeader;

  if (!token) {
    return response.status(401).json({
      msg: 'Token 不能为空'
    });
  }

  jwt.verify(token, encryptToken.jwtSecretKey, (err, decoded) => {
    if (err) {
      return response.status(401).json({
        msg: 'Token已过期'
      });
    }

    // 如果需要在数据库中检查 token
    const sql = 'SELECT * FROM users WHERE token=?';
    let sqlToken = tokenHeader.startsWith('Bearer ') ? tokenHeader : 'Bearer ' + tokenHeader;
    db.query(sql, [sqlToken], (dbError, results) => {
      if (dbError) {
        return response.status(500).json({
          msg: err
        });
      }
      if (results.length > 0) {
        request.user = decoded; // 将解码后的用户信息附加到请求对象上
        next();
      } else {
        return response.status(401).json({
          msg: 'Token 验证失败'
        });
      }
    });
  });
};
